Skip to main content

Memory Optimization

Redis is an in-memory database, meaning performance and cost depend heavily on how efficiently memory is used. Optimizing memory helps you:

  • Reduce RAM usage
  • Improve throughput
  • Lower latency
  • Store more data on the same hardware
  • Prevent eviction due to memory limits

Redis provides several built-in mechanisms and settings to control memory use.

Compression Using Listpacks / Ziplist Encoding

Redis automatically stores small data structures in compact forms:

  • Listpack (newer)
  • Ziplist (older)

Used in:

  • Hashes
  • Lists
  • Sorted sets

Example: Small Sorted Set

ZADD leaders 100 "Alice" 200 "Bob"

Stored as a small optimized list, not a full skiplist + dictionary. This drastically reduces memory.

Bitmaps, Bitfields, and HyperLogLogs

Redis provides specialized structures for massive memory savings.

Using Bitmaps Instead of Sets

Storing user login status (1 million users)

Using a Set

SADD loggedIn 1 5 10 200000
  • A set entry ≈ 50–80 bytes → potentially tens of MB.

Using a Bitmap

SETBIT loginBitmap 200000 1
  • Bitmap uses 1 bit per user
  • 1,000,000 bits → 125 KB only
  • Huge savings compared to large sets

Using HyperLogLog for Approximated Counting

Counting unique visitors:

Using a Set

SADD visitors user123
  • Memory grows unbounded.

Using HyperLogLog (fixed ≈ 12 KB)

PFADD uv user123
PFCOUNT uv

Perfect for:

  • Daily unique visitors
  • Counting unique IPs
  • Measuring cardinality at scale

Memory Policies & Eviction Strategy

Redis can use different eviction policies when memory limit is reached (maxmemory-policy).

Common Policies:

  • allkeys-lru → evict least-recently used keys
  • volatile-lru → LRU but only keys with TTL
  • allkeys-random
  • noeviction (default)
maxmemory 512mb
maxmemory-policy allkeys-lru

Redis automatically frees memory by removing the least-used keys when it reaches 512 MB.